import {Component} from '@angular/core';
import {ApesField} from './apes-field';
import { backField, missing } from '../../../../utils/utils';
import {ApiService} from "@core/services/http/api.service";
import {Events} from "@core/services/events/Events";
import {ExpressionService} from "@core/services/expression/ExpressionService";
import {SubjectService} from "@core/services/events/subject.service";
import { Subject } from 'rxjs/internal/Subject';
import { catchError, debounceTime, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
@Component({
  selector: 'formly-field-select-contract',
  template: `
    <ng-select [items]="itemsData"
               bindLabel="id"
               class="ng-table"
               [hideSelected]="true"
               [optionWidth]="width"
               [disabled]="to.disabled"
               [placeholder]="to.placeholder"
               [formlyAttributes]="field"
               [formControl]="formControl"
               [loading]="contractLoading"
               [typeahead]="contractinput$"
               (change)="backData()"
               (scrollToEnd)="fetchMore()">
      <!-- 表头部分 -->
      <ng-template ng-header-tmp>
        <div apes-row class="ng-table-row">
          <div apes-col class="ng-table-col" [apesSpan]="4">合同号</div>
          <div apes-col class="ng-table-col" [apesSpan]="6">供应商代码</div>
          <div apes-col class="ng-table-col" [apesSpan]="14">供应商名称</div>
        </div>
      </ng-template>

      <ng-template ng-option-tmp let-item="item">
        <div apes-row class="ng-table-row">
          <div apes-col class="ng-table-col" [apesSpan]="4">{{item.id}}</div>
          <div apes-col class="ng-table-col" [apesSpan]="6">{{item.partner.id}}</div>
          <div apes-col class="ng-table-col" [apesSpan]="14">{{item.partner.name}}</div>
        </div>
      </ng-template>
    </ng-select>
  `,
})
export class FormlyFieldSelectContract extends ApesField {
  apesConfig: any;
  private _current = 0;
  width = 0;
  private _pages = 0;
  private _searchText = '';
  contractLoading =false;
  itemsData:any;
  contractinput$ = new Subject<string>();

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService) {
    super(apiService, events, expressionService, subject);
    this.loadContract();
  }

  ngOnInit() {
    this.apesConfig = this.extend(this.to);
    this.width = this.to.width;
  }

  protected extend(data: any) {
    let result = {};
    for (let key in data) {
      let value = data[key];
      result[key] = value;
    }
    return result;
  }
  backData() {
    const context = this.to.context || {};
    backField(this, context);
  }


  private loadContract() {
      this.contractinput$.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        tap(() => this.contractLoading = true),
        switchMap((term) => {
          if (missing(term)) {
            this.contractLoading = false;
            return of([]);
          }
          const data = {page: 0, size: 10,key:term};
          return this.apiService.post("acc.contract.find", data).pipe(
            map((res) =>{
                this.itemsData=[];
                this._searchText = term;
                this.itemsData = this.itemsData.concat(res.content);
                this._current = res.page + 1;
                this._pages = res.pages;
                return res.content
              }
            ),
            catchError(() => of([])), // empty list on error
            tap(() => this.contractLoading = false)
          )})
      ).subscribe();
  }


  fetchMore() {
    this.contractLoading = true;
    // using timeout here to simulate backend API delay
    if (this._current === this._pages || this._searchText == '') {
      this.contractLoading = false;
      return;
    }
    const data = {key: this._searchText, page: this._current, size: 10};
    this.apiService.post("acc.contract.find", data).subscribe(item => {
      this.contractLoading = false;
      if (item.page === 0) {
        this.itemsData = [];
      }
      this.itemsData = this.itemsData.concat(item.content);
      this._current = item.page + 1;
      this._pages = item.pages;
    });

  }
}

